package com.feib.soeasy.action;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.feib.soeasy.model.CodeTable;
import com.feib.soeasy.model.FormatDefinition;
import com.feib.soeasy.model.Group;
import com.feib.soeasy.model.LabelValue;
import com.feib.soeasy.model.P0028Detail;
import com.feib.soeasy.model.Payment;
import com.feib.soeasy.model.UploadFile;
import com.feib.soeasy.pagination.PaginatedList;
import com.feib.soeasy.service.CodeTableService;
import com.feib.soeasy.service.FormatDefinitionService;
import com.feib.soeasy.service.GroupService;
import com.feib.soeasy.service.PaymentService;
import com.feib.soeasy.service.Soez5007Service;
import com.feib.soeasy.util.UserUtil;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.DateTypeConverter;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrors;

/**
 * @title Soez5007ActionBean
 * @description 分戶繳費查詢
 * @author Leo
 * @2011/12/07 create by Leo Lee
 */
public class Soez5007ActionBean extends BaseActionBean {
	
	private static final String DEFAULT_JSP = "/WEB-INF/views/soez5007/soez5007.jsp";
    
    /**
     * 業者代號查詢畫面
     */
    private static final String AJAX_QUERY_GROUP_JSP = "/WEB-INF/views/soez5007/groupPopUpList.jsp";
    /**
     * 分戶繳費查詢結果畫面
     */
    private static final String AJAX_QUERY_JSP = "/WEB-INF/views/soez5007/soez5007List.jsp";
    /**
     * [業者代號]改變後觸發重製[收款類別]選項結果
     */
    private static final String AJAX_FORMT_DEF_OPTIONS_JSP = "/WEB-INF/views/soez5007/formatDefinitionOptions.jsp";
    
    private static final String AJAX_QUERY_DETAIL_JSP = "/WEB-INF/views/soez5007/soez5007Detail.jsp";
    
    /**
     * 查詢條件-資料期間 起
     */
    @Validate( converter=DateTypeConverter.class)
    private Date qryDateFrom;
    
    /**
     * 查詢條件-資料期間 迄
     */
    @Validate( converter=DateTypeConverter.class)
    private Date qryDateTo;
    
    /**
     * 查詢條件--資料期間類型
     * 1: 繳費日期
     * 2: 繳費期限
     */
    private Integer qryDateType;

    /**
     * 查詢條件-收款類別
     */
    private FormatDefinition qryFormatDefinition;
    

    /**
     * 查詢結果
     */
    private PaginatedList<Payment> queryResult;
    
    /**
     * 帳單業者查詢條件
     */
    private Group qryGroup;

    /**
     * 帳單業者查詢結果
     */
    private PaginatedList<Group> queryGroupResult;
    
    /**
     * 查詢單筆Payment
     */
    private Payment qryPayment;
    
    private Payment payment;
    
    /**
     * 收款類別選單
     */
    private List<LabelValue> formatDefinitionoOptions = null;
    
    /**
     * 已繳期數
     */
    private Integer payed;
    
    private List p0028Details;
    
    
    @SpringBean("groupService")
    private GroupService groupService;
    
    @SpringBean("formatDefinitionService")
    private FormatDefinitionService formatDefinitionService;
    
    @SpringBean("codeTableService")
    private CodeTableService codeTableService;
    
    @SpringBean("paymentService")
    private PaymentService paymentService;
    
    @SpringBean("soez5007Service")
    private Soez5007Service soez5007Service;
    
    @DontBind
    @DefaultHandler
    public Resolution doDefault()
    {
        logger.debug("Enter doDefault mehtod.");
        try {
 
            if (!UserUtil.isBankGroup())
            {
                if (null == this.qryPayment)
                    this.qryPayment = new Payment();
                this.qryPayment.setGroup(UserUtil.getUserGroup());
            }
           	
            qryDateTo = getP0028Date();

            Date lastDate = getP0028Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            String lastDateString = dateFormat.format(lastDate);

            String year = lastDateString.substring(0,4);
            String month = lastDateString.substring(4,6);
            String day = lastDateString.substring(6,8);
            
            year = String.valueOf(new Integer(year) -1);
            day = String.valueOf(new Integer(day) + 1);            
            
            qryDateFrom = dateFormat.parse(year + month + day);
        }
        catch (Exception e) {
        }
        return new ForwardResolution(DEFAULT_JSP); 
    }
  
    public Date getP0028Date()
    {
    	try {
    		List codeTables = codeTableService.queryByCodeKind("P0028");
        	CodeTable p0028CodeTable = (CodeTable)codeTables.get(codeTables.size()-1);
        	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        	return dateFormat.parse(p0028CodeTable.getCodeValue());
		} catch (Exception e) {
			logger.error("分戶繳費查詢-P0028Date查詢錯誤(Soez5007ActionBean.getP0028Date):", e);

			return null;
		}
    }
    
    /**
     * 帳單業者查詢
     * @return
     */
    public Resolution doAjaxQueryGroups()
    {
        logger.debug("Enter doAjaxQueryGroups mehtod.");
        try {
            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                throw new Exception("No Authority");
            }
            

            //USER未輸入查詢條件，所以查詢物件會是NULL(查詢物件不可為NULL)
            if (null == qryGroup)
                qryGroup = new Group();

            //呼叫服務查詢
            queryGroupResult = groupService.queryByGroupExcludeBank(qryGroup, queryGroupResult);
        }
        catch (Exception e) {
            logger.error("分戶繳費查詢-帳單業者查詢錯誤(Soez5007ActionBean.doAjaxQueryGroups):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new SimpleError("查詢錯誤") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(AJAX_QUERY_GROUP_JSP);
    }
 
    public Resolution doAjaxQuery()
    {
        logger.debug("Enter doAjaxQuery mehtod.");
        try {
            Date lastDate = getP0028Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            String lastDateString = dateFormat.format(lastDate);
            String year = lastDateString.substring(0,4);
            String month = lastDateString.substring(4,6);
            String day = lastDateString.substring(6,8);
            
            year = String.valueOf(new Integer(year) -1);
            day = String.valueOf(new Integer(day) + 1);
            Date syBeforeYear = dateFormat.parse(year + month + day);
            
            if(syBeforeYear.after(qryDateFrom))
            {
            	// 轉換錯誤訊息
                ValidationErrors errors = new ValidationErrors();
                errors.addGlobalError(new SimpleError("繳款日期(起)不得小於系統日期一年") );
                getContext().setValidationErrors(errors);
                // 回傳 錯誤 HTML fragments
                return super.errorsToHtmlStreams(errors);
            }
            if(getP0028Date().before(qryDateTo))
            {
            	// 轉換錯誤訊息
                ValidationErrors errors = new ValidationErrors();
                errors.addGlobalError(new SimpleError("繳款日期(迄)不得大於P0028日期") );
                getContext().setValidationErrors(errors);
                // 回傳 錯誤 HTML fragments
                return super.errorsToHtmlStreams(errors);
            }
            
            //USER未輸入查詢條件，所以查詢物件會是NULL(查詢物件不可為NULL)
            if (null == this.qryPayment)
                this.qryPayment = new Payment();
            
                   
            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {    
                Group group = new Group();
                group.setGroupPk(UserUtil.getUserGroup().getGroupPk());
                qryPayment.setGroup(group);
            }else
            {
            	
            	qryPayment.setGroup(groupService.findByExactGroupNo(qryPayment.getGroup().getGroupNo()));
            }
            
        	UploadFile uploadFile = new UploadFile();
        	uploadFile.setFormatDefinition(qryFormatDefinition);
        	qryPayment.setUploadFile(uploadFile);

            
            //呼叫服務查詢
            queryResult = soez5007Service.queryResult(qryPayment, qryDateFrom, qryDateTo, queryResult);
            
        }
        catch (Exception e) {
            logger.error("分戶繳費查詢(Soez5007ActionBean.doAjaxQuery):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new SimpleError("查詢錯誤") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(AJAX_QUERY_JSP);
    }
    
    /**
     * 下載Excel
     * @return
     */
    public Resolution doMasterDownloadExcelFile()
    {
        logger.debug("Enter doAjaxDownloadExcelFile mehtod.");
        try {
            if (null == qryDateType || 2 != qryDateType.intValue())
                qryDateType = new Integer(1);
            
            if (null == this.qryPayment)
                this.qryPayment = new Payment();

            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                this.qryPayment.setGroup(UserUtil.getUserGroup());
            }
            else
                this.qryPayment.setGroup(this.groupService.findByExactGroupNo(this.qryPayment.getGroup().getGroupNo()));
            
            //USER未輸入查詢條件，所以查詢物件會是NULL(查詢物件不可為NULL)
            if (null == this.qryPayment)
                this.qryPayment = new Payment();
            
        	UploadFile uploadFile = new UploadFile();
        	uploadFile.setFormatDefinition(qryFormatDefinition);
        	qryPayment.setUploadFile(uploadFile);


            String downloadFilePath = this.soez5007Service.doExportMasterXls(qryPayment, qryDateFrom, qryDateTo);
            if (null == downloadFilePath)
            {
                // 查無資料
            }
            
            File downloadFile = new File(downloadFilePath);
            byte[] bytes = new byte[(int)downloadFile.length()];
            
            BufferedInputStream bufferedInputStream = 
                new BufferedInputStream(new FileInputStream(downloadFile)); 

            bufferedInputStream.read(bytes);

            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            inputStream.close();
            bufferedInputStream.close();
            // 黃郁珊 依問題單修改檔案名稱
            String isoFileName = new String("客戶繳款記錄查詢.xls".getBytes("MS950"), "ISO8859-1");

            StreamingResolution streamingResolution = new StreamingResolution( 
                            "application/vnd.ms-excel",inputStream).setFilename(isoFileName);

            return streamingResolution;
        }
        catch (Exception e) {
            logger.error("", e);
        }
        return new ForwardResolution(DEFAULT_JSP); 
    }
    
    /**
     * 查詢轉入的異常狀態明細資料
     * @return
     */
    public Resolution doAjaxQueryDetail()
    {
        logger.debug("Enter doAjaxQueryDetail mehtod.");
        try {
        	Payment ptt = paymentService.getPaymentByPk(payment);
        	
        	payment.setVirtualAccount(ptt.getVirtualAccount().substring(0,14));
        	payment.setPayerName(ptt.getPayerName());
        	//if(payment.getGroup().getGroupType().equals("4"))
        	//{
        		payed = new Integer(0);
        		try {
        			payment.setPeriod(String.valueOf(new Integer(ptt.getPeriod())));            		
            		List<Payment> ps = paymentService.queryPayementByPayerId(
            				ptt.getPayerId(), ptt.getUploadFile().getUploadFilePk());
            		
            		for(Iterator<Payment> p=ps.iterator();p.hasNext();)
            		{
            			Payment pt = (Payment)p.next();
            			if(pt.getPaymentStatus() == 5)
            				payed = payed + 1;
            		}	
				} catch (Exception e) {
					payment.setPeriod(null);
				}
        		
        	//}
        	
        	//p0028Details = soez5007Service.queryDetail(payment, qryDateFrom, qryDateTo);
        	p0028Details = new ArrayList();
        	List result  = soez5007Service.queryDetail(ptt, qryDateFrom, qryDateTo);
        	if(result != null && result.size() != 0)
    		{
    			for(Iterator<P0028Detail> d=result.iterator();d.hasNext();)
    			{
    				P0028Detail detail = (P0028Detail)d.next();
    				P0028Detail detail2 = new P0028Detail();
    				//detail2 = detail;
    				detail2.setAvbal(detail.getAvbal());
    				if (detail.getMemo().equals("")){
    					detail2.setMemo("銀行");
    				}else{	
    				    detail2.setMemo(detail.getMemo());
    				}    
    				detail2.setTxamt(detail.getTxamt());
    				detail2.setAday(detail.getAday().substring(0,4) + "/" + detail.getAday().substring(4,6) + "/" + detail.getAday().substring(6,8));
    				if(detail.getCrdb().equals("1"))
    					detail2.setCrdb("提");
    				else
    					detail2.setCrdb("存");
    				
    				p0028Details.add(detail2);
    			}
    			
    			
    		}
        	
        }
        catch (Exception e) {
            logger.error("分戶查詢-明細資料查詢錯誤(Soez5007ActionBean.doAjaxQueryDetail):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }
        
        return new ForwardResolution(AJAX_QUERY_DETAIL_JSP);

    }
    
    
    
    public Resolution doAjaxGroupNoChange()
    {
        logger.debug("Enter doAjaxGroupNoChange mehtod.");
        return new ForwardResolution(AJAX_FORMT_DEF_OPTIONS_JSP);
    }
    
    
	public Date getQryDateFrom() {
		return qryDateFrom;
	}
	public void setQryDateFrom(Date qryDateFrom) {
		this.qryDateFrom = qryDateFrom;
	}
	public Date getQryDateTo() {
		return qryDateTo;
	}
	public void setQryDateTo(Date qryDateTo) {
		this.qryDateTo = qryDateTo;
	}
	public Integer getQryDateType() {
		return qryDateType;
	}
	public void setQryDateType(Integer qryDateType) {
		this.qryDateType = qryDateType;
	}
	
	public FormatDefinition getQryFormatDefinition() {
		return qryFormatDefinition;
	}
	public void setQryFormatDefinition(FormatDefinition qryFormatDefinition) {
		this.qryFormatDefinition = qryFormatDefinition;
	}
	public PaginatedList<Payment> getQueryResult() {
		return queryResult;
	}
	public void setQueryResult(PaginatedList<Payment> queryResult) {
		this.queryResult = queryResult;
	}
	public Group getQryGroup() {
		return qryGroup;
	}
	public void setQryGroup(Group qryGroup) {
		this.qryGroup = qryGroup;
	}
	public PaginatedList<Group> getQueryGroupResult() {
		return queryGroupResult;
	}
	public void setQueryGroupResult(PaginatedList<Group> queryGroupResult) {
		this.queryGroupResult = queryGroupResult;
	}
	public Payment getQryPayment() {
		return qryPayment;
	}
	public void setQryPayment(Payment qryPayment) {
		this.qryPayment = qryPayment;
	}
	
	public List<LabelValue> getFormatDefinitionoOptions() {
	       if (null == this.formatDefinitionoOptions)
	        {
	            //如果不是銀行端，則查詢條件要加入帳單業者限制
	            if (!UserUtil.isBankGroup())
	            {
	                // 查詢條件
	                FormatDefinition formatDefinition = new FormatDefinition();
	                Group group = new Group();
	                group.setGroupPk(UserUtil.getUserGroup().getGroupPk());
	                formatDefinition.setGroup(group);
	                formatDefinition.setFormatType(new Integer(1));
	                formatDefinition.setDeleted(Boolean.FALSE);
	                formatDefinitionoOptions = formatDefinitionService.findLabelValueByFormatDefinition(formatDefinition, true);
	            }
	            else
	            {
	                // 銀行端，看是否有群組代碼，若沒有則回傳空陣列
	                if (null != this.qryGroup)
	                {
	                    // 查詢條件
	                    FormatDefinition formatDefinition = new FormatDefinition();
	                    formatDefinition.setGroup(this.qryGroup);
	                    formatDefinition.setDeleted(Boolean.FALSE);
	                    formatDefinition.setFormatType(new Integer(1));
	                    formatDefinitionoOptions = formatDefinitionService.findLabelValueByFormatDefinition(formatDefinition, true);
	                }
	                else
	                {
	                    this.formatDefinitionoOptions = new ArrayList<LabelValue>();                    
	                }

	            }

	        }
	        return formatDefinitionoOptions;
	}
	
	
	public void setFormatDefinitionoOptions(
			List<LabelValue> formatDefinitionoOptions) {
		this.formatDefinitionoOptions = formatDefinitionoOptions;
	}

	public GroupService getGroupService() {
		return groupService;
	}

	public void setGroupService(GroupService groupService) {
		this.groupService = groupService;
	}

	public FormatDefinitionService getFormatDefinitionService() {
		return formatDefinitionService;
	}

	public void setFormatDefinitionService(
			FormatDefinitionService formatDefinitionService) {
		this.formatDefinitionService = formatDefinitionService;
	}

	public PaymentService getPaymentService() {
		return paymentService;
	}

	public void setPaymentService(PaymentService paymentService) {
		this.paymentService = paymentService;
	}

	public Integer getPayed() {
		return payed;
	}

	public void setPayed(Integer payed) {
		this.payed = payed;
	}

	public Payment getPayment() {
		return payment;
	}

	public void setPayment(Payment payment) {
		this.payment = payment;
	}

	public Soez5007Service getSoez5007Service() {
		return soez5007Service;
	}

	public void setSoez5007Service(Soez5007Service soez5007Service) {
		this.soez5007Service = soez5007Service;
	}

	public List getP0028Details() {
		return p0028Details;
	}

	public void setP0028Details(List details) {
		p0028Details = details;
	}

	public CodeTableService getCodeTableService() {
		return codeTableService;
	}

	public void setCodeTableService(CodeTableService codeTableService) {
		this.codeTableService = codeTableService;
	}
    
    
}
